package cn.tedu.bece.front.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.tedu.bece.front.mapper.UserMapper;
import cn.tedu.bece.front.pojo.dto.UserLoginParam;
import cn.tedu.bece.front.pojo.dto.UserQuery;
import cn.tedu.bece.front.pojo.entity.User;
import cn.tedu.bece.front.pojo.vo.UserVO;
import cn.tedu.bece.front.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserVO loginAndRegister(UserLoginParam userLoginParam) {
        UserVO userVO = userMapper.selectByPhone(userLoginParam.getPhone());
        Integer userId ;
        if(userVO==null){
            User user = new User();
            user.setPhone(userLoginParam.getPhone());
            user.setCreateTime(new Date());
            userMapper.insert(user);
            userId = user.getId();
            userVO = new UserVO();
        }else {
            userId = userVO.getId();
        }
        //使用sa-token 进行登录
        StpUtil.login(userId);
        //获取 sa-token 生成的令牌
        String token = StpUtil.getTokenValue();
        log.debug("Sa-Token生成的令牌为：{}",token);
        userVO.setToken(token);
        return userVO;
    }

    @Override
    public UserVO selectUserById(UserQuery userQuery) {
        log.debug("通过id查询用户业务：参数：{}",userQuery);
        UserVO userVO = userMapper.selectUserById(userQuery);
        return userVO;
    }

    @Override
    public void updateUsername(Integer id, String username) {
        log.debug("修改用户名业务，参数：{}，{}",id,username);
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        userMapper.updateUsername(user);
    }

    @Override
    public void updatePhone(Integer id, String phone) {
        log.debug("修改绑定手机号业务，参数：{}，{}",id,phone);
        User user = new User();
        user.setId(id);
        user.setPhone(phone);
        userMapper.updatePhone(user);
    }

}
